#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
 
#define BUFFER_SIZE 1024
 
void Usage() {
    printf("usage: ./server [ip] [port]\n");
}
 
int main(int argc, char *argv[]) {
    if (argc != 3) {
        Usage();
        return 1;
    }
 
    int server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) {
        perror("socket");
        return 1;
    }
 
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(atoi(argv[2]));
    inet_pton(AF_INET, argv[1], &server_addr.sin_addr);
 
    int ret = bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret < 0) {
        perror("bind");
        return 1;
    }
 
    ret = listen(server_fd, 10);
    if (ret < 0) {
        perror("listen");
        return 1;
    }
 
    while (true) {
        struct sockaddr_in client_addr;
        socklen_t len = sizeof(client_addr);
        int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &len);
        if (client_fd < 0) {
            perror("accept");
            continue;
        }
 
        char inputbuf[BUFFER_SIZE] = {0};
        ssize_t read_size = recv(client_fd, inputbuf, BUFFER_SIZE - 1, 0);
        if (read_size < 0) {
            perror("recv");
            close(client_fd);
            continue;
        }
        inputbuf[read_size] = '\0'; // null terminate the string
        printf("%s\n",inputbuf);
        char response[BUFFER_SIZE] = {0};

        const char* hello = "<h1>Hello World</h1>";
        sprintf(response, "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\nContent-Length: %zu\r\n\r\n%s",
                strlen(hello), hello);
 
        send(client_fd, response, strlen(response), 0);
        
    }
 
   
    return 0;
}